package sql

import (
	"log"
	"strings"
	"time"
)

func (sqlOper *SqlOper) InsertFields(one string) (tbname string, head string, bodys string) {
	fields := strings.SplitN(one, " ", 4)
	tbname = sqlOper.ParseTableName(fields[2])
	keyAndValue := strings.SplitN(fields[3], "VALUES", 2)
	head = strings.TrimSpace(keyAndValue[0])
	bodys = strings.TrimSpace(keyAndValue[1])
	return
}

func (sqlOper *SqlOper) ParserInsertHasHead(tableName, head, bodys string, after func(t time.Duration)) {
	// log.Fatal(one)
	st := time.Now()
	defer func() {
		if after != nil {
			after(time.Now().Sub(st))
		}
	}()
	// var err error

	headk := SplitAtCommas(head[1 : len(head)-2])
	headCount := len(headk)
	// onedict := make(Dict)
	items := []Dict{}
	if heads, ok := sqlOper.Tables[tableName]; ok {
		Bodys := strings.Split(bodys, "),")
		BodyCount := len(Bodys)
		for no, entity := range Bodys {
			entity = strings.TrimSpace(entity)
			if entity == "" {
				continue
			}
			entity = entity[1:]

			if no == BodyCount-1 {
				C := false
				for {
					if entity[len(entity)-1] == ')' {
						C = true
					}
					entity = entity[:len(entity)-1]
					if C {
						break
					}
				}
			}
			values := sqlOper.ParseOneBracketValues(entity)
			if len(values) != headCount {
				log.Println("Head      :", headk)
				log.Println("Values    :", strings.Join(values, ","))
				log.Println("Raw value :", entity)
				for nn, vv := range values {
					log.Println("[", nn, "]", vv)
				}
				log.Fatal("Errr Value's Count is not match to Head's Count!", "Head/Value :", headCount, "/", len(values))

			}
			onedict := make(Dict)

			for nov, value := range values {

				key := headk[nov]
				tp := heads[key]
				key = strings.ReplaceAll(key, "`", "")
				if sqlOper.FileType == "mysql" {
					if err := sqlOper.MySqlValue(onedict, tp, key, value); err != nil {
						// log.Println("||", keyAndValue[1])
						log.Fatal("Parse single values", err, "\n|", heads, "\n", no, BodyCount, "|\n")
					}
				} else if sqlOper.FileType == "mssql" {
					if err := sqlOper.MsSqlValue(onedict, tp, key, value); err != nil {
						// log.Println("||", keyAndValue[1])
						log.Fatal("Parse single values", err, "\n|", heads, "\n", no, BodyCount, "|\n")
					}
				}
			}

			items = append(items, onedict)
		}

	}
	if len(items) == 0 {
		log.Fatal(bodys, "\n |-->", "this not parse!!!", tableName)
	} else if len(items) == 1 {
		item := make(Item)
		item[tableName] = items[0]
		sqlOper.DataIn <- item

	} else if len(items) > 1 {
		I := make(map[string][]Dict)
		I[tableName] = items
		sqlOper.DataIns <- I
	}
}

func (sqlOper *SqlOper) ParserInsertNoHead(tableName, bodys string, after func(t time.Duration)) {
	st := time.Now()
	defer func() {
		if after != nil {
			after(time.Now().Sub(st))
		}
	}()

	Bodys := strings.Split(bodys, "),")
	BodyCount := len(Bodys)
	items := []Dict{}
	if heads, ok := sqlOper.Heads[tableName]; ok {
		headCount := len(heads)
		for no, entity := range Bodys {
			entity = entity[1:]
			if no == BodyCount-1 {
				C := false
				for {
					if entity[len(entity)-1] == ')' {
						C = true
					}
					entity = entity[:len(entity)-1]
					if C {
						break
					}
				}
			}
			values := SplitAtCommas(entity)
			if len(values) != headCount {
				log.Fatal("Errr Value's Count is not match to Head's Count!")
			}
			onedict := make(Dict)
			for nov, value := range values {
				keyTp := strings.SplitN(heads[nov], "::", 2)
				key, tp := keyTp[0], keyTp[1]
				key = strings.ReplaceAll(key, "`", "")
				if sqlOper.FileType == "mysql" {
					if err := sqlOper.MySqlValue(onedict, tp, key, value); err != nil {
						// log.Println("||", keyAndValue[1])
						log.Fatal("Parse single values", err, "\n|", heads, "\n", no, BodyCount, "|\n", entity)
					}
				} else if sqlOper.FileType == "mssql" {
					if err := sqlOper.MsSqlValue(onedict, tp, key, value); err != nil {
						// log.Println("||", keyAndValue[1])
						log.Fatal("Parse single values", err, "\n|", heads, "\n", no, BodyCount, "|\n", entity)
					}
				}

			}

			items = append(items, onedict)
		}

	}

	// }
	if len(items) == 1 {
		item := make(Item)
		item[tableName] = items[0]
		sqlOper.DataIn <- item
	} else if len(items) > 1 {
		I := make(map[string][]Dict)
		I[tableName] = items
		sqlOper.DataIns <- I
	}
}
